﻿Imports DevExpress
Imports DevExpress.XtraRichEdit
Imports System.ComponentModel

Public Class DocGen

    'Definition du DocumentTemplate / Le Template a Gauche 
    Public Property DocumentTemplateID As Guid? = Nothing
    'Pour le data a Merger
    Public Property IdOfMergedDoc As Guid? = Nothing
    Public Property ActivatedDocument As Boolean = False
    Public Property DocumentData As String = Nothing

    'Utilisé pour sauvegarder le contenu des document merger dans leur table respective ex: SOPAttribute ou autres...
    'André 2013-06-04
    Public Event SaveMergedDoc(ByVal id As Guid?, ByVal text As String)
    '
    Private _aMetaQuery As CommonExt.MetaQuery
    '
    Private Sub DocGen_Load(sender As Object, e As EventArgs) Handles Me.Load
        'OutStandingIssue: Sera utilisés pour des merges futur.
        Me.DockPanel1.Visibility = Docking.DockVisibility.Hidden
        Me.BarButtonMergeResult.Visibility = BarItemVisibility.Never
        Me.BarButtonMergedFile.Visibility = BarItemVisibility.Never
        '
        If DocumentTemplateID Is Nothing Then
            Dim mainViewAccess As MetaQueryAccess = Nothing
            _aMetaQuery = MetaQuery.GetMetaQueryByName("DocFromDocTemplate")
            If _aMetaQuery IsNot Nothing Then
                _aMetaQuery.FillResultQuery()

                'outstandingissue : will have to check the language and get the 2nd or 3thr column of LOV according to LOV Standard 
                RepositoryItemLookUpEdit1.DataSource = _aMetaQuery.ResultQuery
                RepositoryItemLookUpEdit1.PopulateColumns()
                RepositoryItemLookUpEdit1.Columns("DocumentTemplateId").Visible = False
                RepositoryItemLookUpEdit1.NullText = "(none)"
                RepositoryItemLookUpEdit1.ValueMember = _aMetaQuery.ResultQuery.Columns("DocumentTemplateId").ToString
                RepositoryItemLookUpEdit1.PopupFormSize = New Size(500, 300)
                RepositoryItemLookUpEdit1.DisplayMember = _aMetaQuery.ResultQuery.Columns("Name").ToString
                RepositoryItemLookUpEdit1.BestFitMode = DevExpress.XtraEditors.Controls.BestFitMode.BestFit
                RepositoryItemLookUpEdit1.SearchMode = DevExpress.XtraEditors.Controls.SearchMode.AutoComplete
                RepositoryItemLookUpEdit1.AutoSearchColumnIndex = 1
            End If
        Else
            BarEditItem1.Enabled = False
            If Not ActivatedDocument Then
                '
                ' On load le Template pour avoir la query pour faire le Merge des données
                Me.MetaExtraDocument1.LoadMetaDocument(Me.DocumentTemplateID)
                If Not String.IsNullOrEmpty(Me.DocumentData) Then
                    Me.MetaExtraDocument1.RtfText = DocumentData
                End If
                '
                Dim aMq As MetaQuery = MetaQuery.GetMetaQueryById(MetaExtraDocument1.QueryID)
                If aMq IsNot Nothing Then
                    If Me.IdOfMergedDoc IsNot Nothing AndAlso Not String.IsNullOrEmpty(aMq.GUIDField) Then
                        aMq.SQLWhere = String.Format("{0} = '{1}'", aMq.GUIDField, IdOfMergedDoc.ToString)
                    End If
                    ApplyMqDataSourceForMerging(aMq)
                End If
            Else
                'Me.MetaExtraDocument1.LoadDocument(Me.DocumentStream, DevExpress.XtraRichEdit.DocumentFormat.OpenXml)
                Me.MetaExtraDocument1.ReadOnly = True
            End If
            ' On lock les headers/footers du document quand ce n<est pas le template 
            If IdOfMergedDoc IsNot Nothing Then
                'mARCHE PAS AU SAVE CA DELETE LE HEADERS...
                'Me.MetaExtraDocument1.Options.DocumentCapabilities.HeadersFooters = DocumentCapability.Disabled
            End If
        End If
    End Sub

    Private Sub BarEditItem1_EditValueChanged(sender As Object, e As EventArgs) Handles BarEditItem1.EditValueChanged
        Dim docTemp As DataRow
        Dim Id As Guid = CType(BarEditItem1.EditValue, Guid)
        docTemp = SystemBoxSDK.PL.CoreSDK.DocumentTemplate_PL.GetDocumentTemplateByID(Id)
        If docTemp IsNot Nothing AndAlso Not IsDBNull(docTemp("QueryID_FK")) Then
            Me.MetaExtraDocument1.LoadMetaDocument(Id)
            Id = CType(docTemp("QueryID_FK"), Guid)
            Dim aMq As MetaQuery = MetaQuery.GetMetaQueryById(Id)
            ApplyMqDataSourceForMerging(aMq)
        End If
        '
    End Sub

    Private Sub ApplyMqDataSourceForMerging(ByVal mq As MetaQuery)
        Dim sqlcmd As System.Data.SqlClient.SqlCommand = Nothing
        Dim aParamFrm As MqParamForm
        Dim aExecQuery As DialogResult = DialogResult.OK

        If mq IsNot Nothing Then
            If mq.CommandTypeID = CommonExt.Base.IdRepository.METALIST_METACOMMANDTYPE_SP AndAlso mq.MetaParams.Rows.Count > 0 Then
                aParamFrm = New MqParamForm(mq.QueryName)
                aExecQuery = aParamFrm.ShowDialog()
                'On dit OK pour la form de Parametre
                If aExecQuery = DialogResult.OK Then
                    sqlcmd = mq.InitQueryParams
                    Dim param As SqlClient.SqlParameter
                    For Each row As DataRow In mq.MetaParams.Rows
                        If sqlcmd.Parameters.Contains(row("ColumnName").ToString) Then
                            param = sqlcmd.Parameters(row("ColumnName").ToString)
                            If param IsNot Nothing AndAlso Not IsDBNull(aParamFrm.SelectedParam(row("ColumnName").ToString)) Then
                                param.Value = aParamFrm.SelectedParam(row("ColumnName").ToString)
                            End If
                        Else
                            MessageWindow.ShowMessage(New Exception(String.Format("DocGen execution, SQL Parameter not found: {0}", row("ColumnName"))))
                        End If
                    Next
                ElseIf aExecQuery = DialogResult.Cancel Then
                    Exit Sub
                End If
                'On Passe la sqcmd qui a les paramêtre de rentré
                mq.FillResultQuery(sqlCmd:=sqlcmd)
            Else
                mq.FillResultQuery()
            End If
            '
            ' Assign Result to Richtexteditor
            MetaExtraDocument1.Options.MailMerge.DataSource = Nothing
            MetaExtraDocument1.Options.MailMerge.DataSource = mq.ResultQuery.DefaultView
        Else
            MessageWindow.ShowMessage("Query not found", MsgBoxStyle.Information)
        End If
    End Sub

    'Private Sub BarButtonMergeResult_ItemClick(sender As Object, e As XtraBars.ItemClickEventArgs) Handles BarButtonMergeResult.ItemClick
    '    MetaExtraDocument1.Document.MailMerge(RichEditControl2.Document)
    'End Sub

    'Private Sub RichEditControl2_Enter(sender As Object, e As EventArgs) Handles RichEditControl2.Enter
    '    Me.RichEditBarController1.RichEditControl = Me.RichEditControl2
    'End Sub

    Private Sub RichEditControl1_Enter(sender As Object, e As EventArgs) Handles MetaExtraDocument1.Enter
        Me.RichEditBarController1.RichEditControl = Me.MetaExtraDocument1


    End Sub

    Private Sub SaveInDB_ItemClick(sender As Object, e As XtraBars.ItemClickEventArgs) Handles SaveInDB.ItemClick
        SaveDocumentInDB()
    End Sub

    Private Sub OpenFromDB_ItemClick(sender As Object, e As XtraBars.ItemClickEventArgs) Handles OpenFromDB.ItemClick

    End Sub

    Public Sub SaveDocumentInDB()
        Me.Cursor = Cursors.WaitCursor
        If SaveMergedDocEvent IsNot Nothing AndAlso Me.IdOfMergedDoc IsNot Nothing AndAlso MetaExtraDocument1.Document IsNot Nothing Then
            Using docStream As IO.MemoryStream = New IO.MemoryStream()
                'On envoi le document en mémoire
                'Me.MetaExtraDocument1.SaveDocument(docStream, DevExpress.XtraRichEdit.DocumentFormat.OpenXml)
                'docStream.Position = 0
                RaiseEvent SaveMergedDoc(Me.IdOfMergedDoc, Me.MetaExtraDocument1.RtfText)
            End Using
        Else
            'On arrive de DocumentTemplate... On veux
            MetaExtraDocument1.SaveMetaDocument()
        End If
        Me.Cursor = Cursors.Default
    End Sub


    Public Sub New()
        ' This call is required by the designer.
        InitializeComponent()
        '
        ' Add any initialization after the InitializeComponent() call.
        Me.MetaExtraDocument1.Options.DocumentSaveOptions.DefaultFormat = DocumentFormat.Rtf
        Me.MetaExtraDocument1.Options.DocumentSaveOptions.DefaultFileName = "DocumentTemplate"
        Me.RichEditControl2.Options.DocumentSaveOptions.DefaultFormat = DocumentFormat.Rtf
        Me.RichEditControl2.Options.DocumentSaveOptions.DefaultFileName = "DocumentTemplateSample"
    End Sub
End Class